package com.swallow.cloud.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.swallow.cloud.entity.Menu;
import com.swallow.cloud.mapper.MenuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: L.swallow
 * @Date: 2019/3/5 16:32
 */
@Service
public class MenuService extends ServiceImpl<MenuMapper, Menu> implements IService<Menu> {


    public List<Menu> selectTreeList() {
            return getAllMenuList(null);
    }


    private List<Menu> getAllMenuList(Long userId) {

        List<Menu> menuList = super.list(new QueryWrapper<>(new Menu("0")));

        //递归获取子菜单
        getMenuTreeList(menuList, null);

        return menuList;
    }

    private List<Menu> getMenuTreeList(List<Menu> menuList, List<String> menuIdList) {
        List<Menu> subMenuList = new ArrayList<>();

        for(Menu entity : menuList){
            //目录
            if(entity.getType().equals(0)){
                entity.setList(getMenuTreeList(queryListParentId(entity.getId(), menuIdList), menuIdList));
            }
            subMenuList.add(entity);
        }

        return subMenuList;
    }

    public List<Menu> queryListParentId(String parentId, List<String> menuIdList) {
        List<Menu> menuList =  super.list(new QueryWrapper<>(new Menu(parentId)));
        if(menuIdList == null){
            return menuList;
        }

        List<Menu> userMenuList = new ArrayList<>();
        for(Menu menu : menuList){
            if(menuIdList.contains(menu.getId())){
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }
}
